package com.jmu.edu.IMApplication.fragment;

import android.os.Bundle;

import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentTransaction;

import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import com.google.android.material.button.MaterialButton;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.jmu.edu.IMApplication.MyApplication;
import com.jmu.edu.IMApplication.R;
import com.jmu.edu.IMApplication.net.bean.Match;
import com.jmu.edu.IMApplication.utils.HttpUtil;
import com.jmu.edu.IMApplication.utils.JiebaUtils;
import com.jmu.edu.IMApplication.utils.ViewUtils;
import com.liys.dialoglib.LAnimationsType;
import com.liys.dialoglib.LDialog;
import com.wang.avi.AVLoadingIndicatorView;

import java.io.IOException;
import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;


public class MatchFragment extends Fragment {
    private static final String TAG = "match";
    private MaterialButton matchButton;
    private LDialog dialog;
    private AVLoadingIndicatorView animation;
    private List<Match> matchList;


    public MatchFragment() {
        // Required empty public constructor
    }


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_match, container, false);
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        initView();
    }

    private void initView() {
        matchButton = getView().findViewById(R.id.fragment_match_start);
        animation = getView().findViewById(R.id.fragment_match_animation);
        initListener();
        initDialog();
    }

    private void match() {
        //先开始播放加载动画
        animation.setVisibility(View.VISIBLE);
        animation.show();
        //加载数据--这里后续需要封装，回调应该写在这个方法里，目前回调也在下面这个方法中，所以后续的跳转也是在里面
        getMatchListFromServer();
    }

    private void getMatchListFromServer() {
        Map<String, String> map = new HashMap<>();
        map.put("username", MyApplication.getUser().getUserName());
        RequestBody requestBody = RequestBody.create(HttpUtil.JSON, new Gson().toJson(map));
        Request request = new Request.Builder().url(HttpUtil.URL_GET_MATCH_LIST).post(requestBody).build();
        MyApplication.getClient().newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.e(TAG, "onFailure: ", e);
                //结束加载动画
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        animation.hide();
                    }
                });
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                //结束加载动画
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        animation.hide();
                    }
                });
                String json = response.body().string();
                Log.d(TAG, "onResponse: " + json);
                TypeToken<List<Match>> typeToken = new TypeToken<List<Match>>() {
                };
                matchList = new Gson().fromJson(json, typeToken.getType());
                if (matchList == null) {
                    getActivity().runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(getContext(), "已经没有新的匹配用户啦！请稍后再试！", Toast.LENGTH_SHORT).show();
                        }
                    });
                } else {
                    jumpToMatchResultFragment();
                }
            }
        });
    }

    private void jumpToMatchResultFragment() {
        //设置要展示的Match列表
        MatchResultFragment matchResultFragment = new MatchResultFragment();
        matchResultFragment.setMatchList(matchList);
        //跳转到MatchResultFragment
        ViewUtils.showFragment(matchResultFragment, TAG);
    }

    private void initListener() {
        matchButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //这里要先获取自己的爱好列表，如果自己的爱好列表为空，那么提醒用户补全信息或是直接开始匹配
                //showDialog();
                match();
            }
        });
    }

    private void showDialog() {
        dialog.show();
    }

    private void initDialog() {
        dialog = LDialog.newInstance(getContext(), R.layout.layout_match_dialog);
        dialog
                .setMaskValue(0.5f) //遮罩--透明度(0-1)
                //3.设置背景
                //颜色
//                .setBgColor(Color.WHITE) //一种颜色
//                .setBgColor("#FFFFFF") //一种颜色
//                .setBgColor(GradientDrawable.Orientation.BOTTOM_TOP, Color.BLUE, Color.YELLOW) //颜色渐变(可传多个) 参数1：渐变的方向
//                .setBgColor(GradientDrawable.Orientation.BOTTOM_TOP, "#00FEE9", "#008EB4") //颜色渐变(可传多个)
//                .setBgColorRes(R.color.white) //一种颜色(res资源)
//                .setBgColorRes(GradientDrawable.Orientation.BOTTOM_TOP, R.color.colorAccent, R.color.colorPrimary) //颜色渐变(可传多个)
                //圆角
                .setBgRadius(15) //圆角, 单位：dp
//                .setBgRadius(5, 5, 0, 0) //圆角, 单位：dp
//                .setBgRadiusPX(10) //圆角, 单位：px
//                .setBgRadiusPX(10, 10, 10, 10) //圆角, 单位：px

                //4.设置弹框位置
                .setGravity(Gravity.CENTER) //弹框位置
                //.setGravity(Gravity.LEFT, 0, 0) //弹框位置(偏移量)

                //5.设置动画
                //5.1 内置动画(平移，从各个方向弹出)
                // 对应的值：DEFAULT(渐变) (LEFT TOP RIGHT BOTTOM 平移)  SCALE(缩放)
                .setAnimations(LAnimationsType.SCALE)
                //5.2 自定义动画
                //.setAnimationsStyle(R.style.li_dialog_default) //设置动画

                //6.设置具体布局
                //6.1 常见系统View属性
//                .setText(R.id.tv_title, "确定")
//                .setTextColor()
//                .setTextSize()
//                .setTextSizePX()
//                .setBackgroundColor()
//                .setBackgroundRes()
//                .setImageBitmap()
//                .setVisible()
//                .setGone()
                //6.2 其它属性
                //.setCancelBtn(R.id.tv_cancel, R.id.tv_confirm) //设置按钮，点击弹框消失(可以传多个)
                .setOnClickListener(new LDialog.DialogOnClickListener() { //设置按钮监听
                    @Override
                    public void onClick(View v, LDialog customDialog) {
                        if (v.getId() == R.id.layout_match_dialog_confirm) {
                            ShowTagFragment showTagFragment = (ShowTagFragment) MyApplication.fragmentManager.findFragmentByTag("showTag");
                            if (showTagFragment == null) {
                                showTagFragment = new ShowTagFragment();
                            }
                            showTagFragment.setUserInfo(MyApplication.getUser());
                            ViewUtils.showFragment(showTagFragment, "showTag", R.anim.from_right, R.anim.out_right);
                        } else {
                            //这里直接开始匹配
                            match();
                        }
                        customDialog.dismiss();
                    }
                }, R.id.layout_match_dialog_confirm, R.id.layout_match_dialog_refuse);  //可以传多个

    }
}